package com.mdc.hispringsecurity;

//import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
//import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.password.StandardPasswordEncoder;

import javax.sql.DataSource;

// @Configuration 和 @EnableWebSecurity 只要有一个即可。
@Configuration
//@EnableWebSecurity
// 该注释也可以放在SpringBootApplication中，但必须在本类中有@Configuration相配合
public class WebSecurityConfig
        extends WebSecurityConfigurerAdapter {

    // 如果没有configure，只有configureGlobal，则访问任何页面都需要认证
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
                .antMatchers("/hello").access("hasRole('ADMIN')")//and hasIpAddress('192.168.1.102') '127.0.0.1'
                .antMatchers("/", "/home").permitAll()
                .antMatchers(HttpMethod.POST,"/spittles").authenticated()
                .anyRequest().authenticated()
                .and()
            .rememberMe() //启用“记住我"功能
                .tokenValiditySeconds(2419200)
                .key("SSDKey") //这里SSDKey仅仅是秘钥（私钥），而不是加密算法；测试：若更改了秘钥，“记住我"不起作用，需要重新登录
                .and()
            /*.requiresChannel()
                .antMatchers("/login").requiresSecure()
                .and()*/
            .formLogin()
                .loginPage("/login").permitAll()
                .and()
            .logout().permitAll();
    }

    /*@Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication()
                .withUser("aa").password("123").authorities("USER")
                .and()
                .withUser("admin").password("admin").roles("USER", "ADMIN");//.authorities("ROLE_ADMIN");
    }*/

    @Autowired
    DataSource dataSource;
    @Override
    public void configure(AuthenticationManagerBuilder auth) throws Exception {
        /*可以同时使用基于内存的用户存储和基于数据库的用户存储*/
        auth.jdbcAuthentication().dataSource(dataSource)
                .usersByUsernameQuery("select username, password, enabled from account where username=?")
                .authoritiesByUsernameQuery("select username, role from account_role where username=?");
                //.passwordEncoder(new StandardPasswordEncoder("53cr3t"));

        auth.inMemoryAuthentication()
                .withUser("aa").password("123").roles("USER")//.authorities("USER")
                .and()
                .withUser("admin").password("admin").roles("USER", "ADMIN");//.authorities("ROLE_ADMIN");
    }

}